package yuan.node;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @version: 1.0
 * @Description: TODO
 * @author: zZmH
 * @date: 2020/09/12 21:12
 */


public class CuratorLock {
    public static final String ip = "192.168.190.128:2181";
    CuratorFramework client;

    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory
                .builder()
                .connectString(ip)
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .namespace("create")
                .build();
        client.start();

    }

    @After
    public void after() {
        client.close();
    }

    //排它锁
    @Test
    public void test1() throws Exception {
        InterProcessMutex interProcessMutex = new InterProcessMutex(client, "/lock1");
        System.out.println("等待获取锁");
        interProcessMutex.acquire();
        for (int i = 0; i < 10; i++) {
            Thread.sleep(3000);
            System.out.println(i);
        }
        interProcessMutex.release();
        System.out.println("释放锁");
    }

    @Test
    public void test2() throws Exception {
        InterProcessReadWriteLock readWriteLock = new InterProcessReadWriteLock(client, "/lock1");
        InterProcessMutex readLock = readWriteLock.readLock();
        InterProcessMutex writeLock = readWriteLock.writeLock();
        System.out.println("获取read锁");
        readLock.acquire();
        System.out.println("获取到读锁了");
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1);
            System.out.println(i);
        }
        readLock.release();
        System.out.println("释放readLock");
    }

    @Test
    public void test3() throws Exception {
        InterProcessMutex interProcessMutex = new InterProcessMutex(client, "/lock1");
    }

}
